//
//  LoginViewController.m
//  Estate
//
//  Created by heyong on 16/5/25.
//  Copyright © 2016年 ttsx. All rights reserved.
//
#define SCREEN_FRAME ([UIScreen mainScreen].bounds)
#import <sys/utsname.h>
#import "LoginViewController.h"
#import "EsTabBarController.h"
#import "userModel.h"
#import "CommonFunc.h"
#import "dataInit.h"

@interface LoginViewController ()

@property (nonatomic,strong)  NSMutableArray *userArr;

@property(nonatomic,strong)FMDatabase *db;

@end

@implementation LoginViewController

-(personRoleView *)roleView{
    if (!_roleView) {
        _roleView = [[personRoleView alloc]initWithFrame:self.view.bounds];
        _roleView.backgroundColor=[[UIColor blackColor]colorWithAlphaComponent:0.5];
        _roleView.layer.cornerRadius = 5;
        
    }
    return _roleView;
}

- (FMDatabase *)db{
    if(_db==nil){
        _db=[FMDatabase databaseWithPath:DEF_DB_DATABASEPATH];
    }
    return _db;
}
-(NSMutableArray *)userArray{
    if(_userArray==nil){
        _userArray=[NSMutableArray array];
    }
    return _userArray;
}
-(UIScrollView *)scrollView{
    if(_scrollView==nil){
        _scrollView=[[UIScrollView alloc]initWithFrame:SCREEN_FRAME];
        _scrollView.pagingEnabled=YES;
    }
    return _scrollView;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    NSLog(@"%@", DEF_DB_DATABASEPATH);

    if(self.flag==nil){
        [self judgeWelcomePageView];
    }
    [self createStyle];
    // 创建文件管理器
    NSFileManager *manager=[NSFileManager defaultManager];
    // 判断指定路径是否存在
    if (![manager fileExistsAtPath:DEF_DB_DATABASEPATH]) {
        [manager copyItemAtPath:[[NSBundle mainBundle] pathForResource:DEF_DB ofType:@""] toPath:DEF_DB_DATABASEPATH error:nil];
    }
    self.userArr = DEF_PERSISTENT_GET_OBJECT(@"userarray");
    self.jlBtn.hidden=YES;
    self.sgfbtn.hidden=YES;
    self.zjbtn.hidden=YES;
    
    // 取出用户名与密码(utf- 8转汉字)
    NSString *userName = [CommonFunc textFromBase64String
                          :DEF_PERSISTENT_GET_OBJECT(@"loginuser")];
    NSString *passWord = [CommonFunc textFromBase64String:DEF_PERSISTENT_GET_OBJECT(@"password")];
    
    // 设置用户名和密码
    self.userName.text = userName;
    self.passWord.text = passWord;
    //没网
    if (self.isShow) {
        self.isCon=NO;
    }else{
        [LSHttpTool checkNetWork:^(NSString *status) {
            if([status isEqualToString:@"0"]){
                self.isCon=NO;
                [LSUtility showToastWithMessage:@"请连接网络！" inView:self.view Andtime:1.];
            }else{
                self.isCon=YES;
            }
        }];
    }
  
}

#pragma mark -设置样式
- (void)createStyle {
    //输入框样式
    [self setTextFieldStyle:self.userName AndMsg:@"用户名" AndImage:@"renxiang_03"];
    [self setTextFieldStyle:self.passWord AndMsg:@"密码" AndImage:@"mima_03"];
    //登录按钮样式
    [self.loginBtn setTitleColor:[UIColor colorWithRed:0.40 green:0.74 blue:0.65 alpha:1.00] forState:UIControlStateNormal];
    self.loginBtn.layer.cornerRadius=4.;
    self.loginBtn.backgroundColor=[[UIColor whiteColor] colorWithAlphaComponent:0.5];
    //底部文字
    self.companyLab.textColor=[UIColor colorWithRed:0.60 green:0.71 blue:0.22 alpha:1.00];
    self.companyLab.text=APP_COPYRIGHT;
}

//设置输入框样式
- (void)setTextFieldStyle:(UITextField *)field AndMsg:(NSString *)msg AndImage:(NSString *)imgStr{
    field.backgroundColor=[UIColor clearColor];
    field.layer.borderColor=[UIColor colorWithRed:0.83 green:0.92 blue:0.85 alpha:1.00].CGColor;
    field.layer.borderWidth=1.;
    field.textColor=[UIColor whiteColor];
    [field setValue:[[UIColor whiteColor] colorWithAlphaComponent:0.9]
         forKeyPath:@"_placeholderLabel.textColor"];
    field.clearButtonMode = UITextFieldViewModeWhileEditing;
    //添加左视图
    UIView *view1=[[UIView alloc]init];
    view1.frame=CGRECTS(0, 0, 50, 40);
    
    //设置图标
    UIImageView *image=[[UIImageView alloc]initWithImage:[UIImage imageNamed:imgStr]];
    image.frame=CGRECTS(8, 8, 22, 23);
    field.placeholder=msg;
    
    //设置分割线
    UIView *row=[[UIView alloc]initWithFrame:CGRECTS(40, 12, 1, 15)];
    row.backgroundColor=[UIColor whiteColor];
    [view1 addSubview:row];
    
    [view1 addSubview:image];
    field.leftViewMode=UITextFieldViewModeAlways;
    field.leftView=view1;
}

- (IBAction)ClickLogin:(UIButton *)sender {
    [self.view endEditing:YES];
    if([self.userName.text isEqualToString:@""]){
        [LSUtility showToastWithMessage:@"请输入用户名" inView:self.view Andtime:1.];
    }else if([self.passWord.text isEqualToString:@""]){
        [LSUtility showToastWithMessage:@"请输入密码" inView:self.view Andtime:1.];
    }else{
        self.isCon = [LSHttpTool reachability];
        if(self.isCon){
            //密码验证
            [self PwdVerify];
        }else{
            [LSUtility showToastWithMessage:@"请连接网络！" inView:self.view Andtime:1.];
        }
    }
}


- (IBAction)clickForgetBtn:(UIButton *)sender {
    MultipleIPSettingController *ipsetCtr=[[MultipleIPSettingController alloc]init
                                           ];
    [self presentViewController:ipsetCtr animated:YES completion:^{
    }];
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    [self.view endEditing:YES];
}


#pragma mark-验证密码
- (void)PwdVerify {
    
    WEAKSELF
    //汉字转 utf- 8
    NSString *userName = [CommonFunc base64StringFromText
                          :_userName.text ];
    NSString *passWord = [CommonFunc base64StringFromText:_passWord.text];
    
    //登录时清除登录名密码  登录成功再持久化
    DEF_PERSISTENT_REMOVE(@"loginuserPost");
    
    [LSUtility showMBProgress:self.view message:@"登录中"];
    
    //记录设备id
    if (![HYKeyChain keyChainLoad]) {
        NSString *deviceId=[[[UIDevice currentDevice] identifierForVendor] UUIDString];
        //存入设备id
        [HYKeyChain keyChainSave:deviceId];
    }
    
    NSString *saveId=[HYKeyChain keyChainLoad];
    
    DEF_PERSISTENT_SET_OBJECT(saveId, @"deviceId");
    
    //    DeLog(@"SAVEID:%@",saveId);
    
    //记录账号登录名 退出账号是使用此参数
    DEF_PERSISTENT_SET_OBJECT(_userName.text,@"loginUserss");
    
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    [parameters setObject:userName forKey:@"username"];
    [parameters setObject:passWord forKey:@"password"];
    [parameters setObject:saveId forKey:@"phoneId"];
    [parameters setObject:@"true" forKey:@"loginState"];
    [parameters setObject:[self iphoneType] forKey:@"phoneModel"];
    [parameters setObject:[UIDevice currentDevice].systemVersion forKey:@"phoneSystemVersion"];
    [parameters setObject:@"iOS" forKey:@"phoneTerminal"];

    [LSHttpTool Post:URL_LOGIN parameters:parameters success:^(id responseObject) {
        NSLog(@"responseObject:%@ \n msg:%@",responseObject,responseObject[@"msg"]);

        NSDictionary *userDic=responseObject[@"data"];
        if ([responseObject[@"code"]isEqualToString:@"0"]) {
            [LSUtility hideMBProgress:self.view];
     
        } else if([responseObject[@"code"]isEqualToString:@"1"]) {
            // 记录用户名
            DEF_PERSISTENT_SET_OBJECT(userName, @"loginuser");
            // 记录用户名传参使用
            DEF_PERSISTENT_SET_OBJECT(userName, @"loginuserPost");
            // 记录密码
            DEF_PERSISTENT_SET_OBJECT(passWord, @"password");
            
            //记录真实姓名
            NSString *realName = userDic[@"realname"];
            DEF_PERSISTENT_SET_OBJECT(realName, @"realname");
            
            //记录项目类型
            NSString *proType = userDic[@"proType"];
            DEF_PERSISTENT_SET_OBJECT(proType, @"proType");

            NSMutableArray *roleArray=[NSMutableArray array];
            // 得到默认项目id
            NSString *proId = userDic[@"proId"];
            // 得到用户关联项目id和身份
            NSArray *userProArr = userDic[@"proRoleList"];
    
            //存在默认项目id
            if(proId){
                for (NSDictionary *dic in userProArr) {
                    if([proId isEqualToString:dic[@"proId"]]){
                        //去重
                        if(![roleArray containsObject:dic]){
                            [roleArray addObject:dic];
                        }
                    }
                }
            } else {
                // 不存在默认项目
                for (NSDictionary *dic in userProArr) {
                    if(dic[@"proId"]){
                        //去重
                        if(![roleArray containsObject:dic]){
                            [roleArray addObject:dic];
                        }
                    }
                }
            }
         
            //角色大于2个
            if(roleArray.count>1){
                self.roleView=nil;
                //此处选择角色
                [self.view addSubview:self.roleView];
                //设置用户名
                self.roleView.userName.text=[NSString stringWithFormat:@"  %@",userDic[@"realname"]];
                //去掉重复的类型
                self.roleView.dataArray = roleArray;
            
                // 点击确定
                self.roleView.sureBlock=^(NSDictionary *roleOrPro){
                    if(!roleOrPro){
                        [LSUtility showToastWithMessage:@"请选择角色" inView:weakSelf.view Andtime:1.];
                        [weakSelf loginFailure];
                        return ;
                    }
                    NSLog(@"roleOrPro:%@",roleOrPro);
                    //判断该角色是否有页面
                    NSString *type=roleOrPro[@"userType"];
                    if(![USERTYPE.userTypeArray containsObject:type]){
                        [LSUtility showToastWithMessage:@"该角色不存在页面，请重新选择角色！" inView:weakSelf.view Andtime:1.5];
                        [weakSelf loginFailure];
                        return;
                    }
                    
                    [weakSelf.roleView removeFromSuperview];
                   
                    
                   if([weakSelf.flag isEqualToString:@"shanchu"]){
                        [weakSelf cleanDataForDic:roleOrPro andUserDic:userDic];
                       [weakSelf loginFailure];
                        return ;
                   }else{
                       //判断 当前ip和上次退出ip是否相同
                       NSString *oldIp= DEF_PERSISTENT_GET_OBJECT(@"oldServiceIP");
                       if([DEFIP isEqualToString:oldIp]){
                           /*
                            *  判断是否初始化数据
                            */
                           bool isExist;
                           if([weakSelf.userArr containsObject:weakSelf.userName.text]){
                               isExist=YES;
                           }else{
                               isExist=NO;
                           }
                           if(!isExist){
                               /*
                                *  初始化数据
                                */
                               NSMutableDictionary *parameDic=[NSMutableDictionary dictionary];
                               
                               [LSUtility showMBProgress:weakSelf.view message:@"数据获取中.."];
                               [LSHttpTool Post:URL_DATA_SYNCHRONIZATION parameters:parameDic success:^(id responseObject) {
                                   
                                   [LSUtility hideMBProgress:weakSelf.view];
                                   
                                   NSLog(@"初始化：%@",responseObject);
                                   if(responseObject){
                                       dataInit *initData=[[dataInit alloc]init];
                                       NSDictionary *dic=responseObject[@"data"];
                                       //没有返回数据
                                       if([[dic allKeys] containsObject:@"total"]){
                                           [LSUtility showToastWithMessage:@"请先在pc端设置数据" inView:weakSelf.view Andtime:1.5];
                                           [weakSelf loginFailure];
                                           return ;
                                       }
                                       //传入数据
                                       [initData initWithResponseObject:responseObject[@"data"]];
                                       [MBProgressHUD hideHUDForView:weakSelf.view animated:YES];
                                       
                                       initData.blockMainTab=^(){
                                           // 初始化用户名写入文件
                                           [weakSelf durationUser:weakSelf.userName.text];
                                           //初始化完成 跳转
                                           EsTabBarController *tabMain=[[EsTabBarController alloc]init];
                                           [tabMain setProId: roleOrPro[@"proId"] setProType:roleOrPro[@"proType"] andUserId:userDic[@"userId"] andRole:roleOrPro[@"userType"]];
                                           [[UIApplication sharedApplication].delegate window].rootViewController=tabMain;
                                       };
                                       
                                   }else{
                                       [LSUtility showToastWithMessage:@"请先在pc端设置数据" inView:weakSelf.view Andtime:1.5];
                                       [LSUtility hideMBProgress:weakSelf.view];
                                       [weakSelf loginFailure];
                                       return ;
                                   }
                                   
                               } failure:^(NSError *error) {
                                   NSLog(@"超时");
                                   [LSUtility hideMBProgress:weakSelf.view];
                                   [weakSelf loginFailure];
                               }];
                               [MBProgressHUD hideHUDForView:weakSelf.view animated:YES];
                               
                           }else{
                               NSLog(@"已经初始化351");
                               EsTabBarController *tabMain=[[EsTabBarController alloc]init];
                               [tabMain setProId: roleOrPro[@"proId"] setProType:roleOrPro[@"proType"] andUserId:userDic[@"userId"] andRole:roleOrPro[@"userType"]];
                               [[UIApplication sharedApplication].delegate window].rootViewController=tabMain;
                               [MBProgressHUD hideHUDForView:weakSelf.view animated:YES];
                           }
                       }else{
                           /*
                            *  清空数据 重新初始化
                            */
                           [weakSelf cleanDataForDic:roleOrPro andUserDic:userDic];
                           
                       }
                       
                   }
                                        
                };
                
            } else {
               
                //只有一个角色直接初始化登录
                NSDictionary *dicss=[roleArray firstObject];
                //如果是删除
                if([weakSelf.flag isEqualToString:@"shanchu"]){
                    [weakSelf cleanDataForDic:dicss andUserDic:userDic];
                }else{
                    //判断 当前ip和上次退出ip是否相同
                    NSString *oldIp= DEF_PERSISTENT_GET_OBJECT(@"oldServiceIP");
                    
                    if([DEFIP isEqualToString:oldIp]){
                        NSLog(@"ip相同");
                        bool isExist;
                        if([weakSelf.userArr containsObject:weakSelf.userName.text]){
                            isExist=YES;
                        }else{
                            isExist=NO;
                        }
                        NSString *type=dicss[@"userType"];
                        if(![USERTYPE.userTypeArray containsObject:type]){
                            [MBProgressHUD hideHUDForView:weakSelf.view animated:YES];
                            if(!type){
                                [LSUtility showToastWithMessage:@"当前登录角色无移动端页面,请在电脑端设置！"  inView:weakSelf.view Andtime:2.5];
                            } else {
                                [MBProgressHUD hideHUDForView:weakSelf.view animated:YES];
                                [LSUtility showToastWithMessage:@"当前登录角色无移动端页面,请在电脑端设置！" inView:weakSelf.view Andtime:2.5];
                            }
                            [self loginFailure];
                            return;
                        }
                        //只有一个角色 并且是领导
                        if([type isEqualToString:@"LEADER_01"]){
                            
                            
                        }else{
                            if(!isExist){
                                /*
                                 *  初始化数据
                                 */
                                NSMutableDictionary *parameDic=[NSMutableDictionary dictionary];
                                
                                [LSHttpTool Post:URL_DATA_SYNCHRONIZATION parameters:parameDic success:^(id responseObject) {
                                    [LSUtility hideMBProgress:weakSelf.view];
                                    
                                    dataInit *initData=[[dataInit alloc]init];
                                    NSDictionary *dic=responseObject[@"data"];
                                    NSLog(@"初始化list:%@",dic);
                                    if(dic){
                                        //没有返回数据
                                        if([[dic allKeys] containsObject:@"total"]){
                                            [LSUtility showToastWithMessage:@"请先在pc端设置此用户数据!" inView:weakSelf.view Andtime:1.5];
                                            [self loginFailure];
                                            return ;
                                        }
                                        //传入数据
                                        [initData initWithResponseObject:responseObject[@"data"]];
                                        [MBProgressHUD hideHUDForView:weakSelf.view animated:YES];
                                        
                                        initData.blockMainTab=^(){
                                            // 初始化用户名写入文件
                                            [weakSelf durationUser:weakSelf.userName.text];
                                            EsTabBarController *tabMain=[[EsTabBarController alloc]init];
                                            [tabMain setProId: dicss[@"proId"] setProType:dicss[@"proType"] andUserId:userDic[@"userId"] andRole:dicss[@"userType"]];
                                            [[UIApplication sharedApplication].delegate window].rootViewController=tabMain;
                                            
                                        };
                                        
                                    }else{
                                        
                                        [LSUtility showToastWithMessage:@"请先在pc端设置此用户数据!" inView:weakSelf.view Andtime:1.5];
                                        [self loginFailure];
                                        return ;
                                    }
                                    
                                    
                                } failure:^(NSError *error) {
                                    [self loginFailure];
                                    NSLog(@"超时");
                                    [LSUtility hideMBProgress:weakSelf.view];
                                    [MBProgressHUD hideHUDForView:weakSelf.view animated:YES];
                                    
                                }];
                            }else{
                                EsTabBarController *tabMain=[[EsTabBarController alloc]init];
                                [tabMain setProId: dicss[@"proId"]  setProType:dicss[@"proType"] andUserId:userDic[@"userId"] andRole:dicss[@"userType"]];
                                [[UIApplication sharedApplication].delegate window].rootViewController=tabMain;
                                [MBProgressHUD hideHUDForView:weakSelf.view animated:YES];
                            }
                        }
                        
                    }else{
                        
                        [weakSelf cleanDataForDic:dicss andUserDic:userDic];
                        
                    }
                }
                
            }
            
            self.roleView.cancelBlock=^{
                [LSUtility hideMBProgress:weakSelf.view];
                [weakSelf.roleView removeFromSuperview];
                [weakSelf loginFailure];
            };
            
        }else{
            [weakSelf loginFailure];
            [LSUtility hideMBProgress:self.view];
            [MBProgressHUD showError:@"服务器数据异常！" toView:self.view];
            
        }
    } failure:^(NSError *error) {
        [self loginFailure];
        [LSUtility hideMBProgress:self.view];
        [LSUtility showToastWithMessage:@"服务器或网络异常，请稍后再试！" inView:self.view Andtime:2.];
    }];
}

-(void)loginFailure{
    
    NSMutableDictionary *parameter= [NSMutableDictionary dictionary];
    [LSHttpTool Post:URL_LOGINFailure parameters:parameter success:^(id responseObject) {
        NSLog(@"%@",responseObject);
        
    } failure:^(NSError *error) {
        NSLog(@"%@",error);
    }];

}
/*
 *  登录过的用户持久化、下次不再初始化数据
 */
-(void)durationUser:(NSString *)userName{
    [self.userArray addObject:userName];
    DEF_PERSISTENT_SET_OBJECT(self.userArray, @"userarray");
}

- (NSString *)loginForProId:(NSString *)proid andUserID :(NSString *)userId{
    [self.db open];
    NSString *sql=[NSString stringWithFormat:@"SELECT * FROM PROJECT_USER WHERE PRO_ID = '%@'  AND USER_ID='%@'",proid,userId];
    FMResultSet *result = [self.db executeQuery:sql];
    [self.db close];
    return [result stringForColumn:@"USER_TYPE"];
}


#pragma mark -清空数据
-(void)cleanDataForDic:(NSDictionary *)roleOrPro andUserDic:(NSDictionary *)userDic{
    NSInteger num=0;
    FMDatabase *db = [FMDatabase databaseWithPath:DEF_DB_DATABASEPATH];
    [db open];
    NSArray *tableArray=@[WORK_LOG, SYSTEM_CONFIG, ADDRESS, UNIT, USER, PROJECT_UNIT, PROCESS, PROCESS_RECORD, PROJECT, PROJECT_USER, PRO_ENGINEER_SURVEY, WORK_DIARY, WORK_RECORD, ADVERTISING_PICTURE, ATTACHMENT, SAMPLE_PROCESS, SAMPLE_PROCESS_RECORD, SAMPLE_CODE, INSPECT_PROCESS, INSPECT_PROCESS_RECORD, INSPECT_ITEM, INSPECT_USER_ITEM, INSPECT_GROUP, INSPECT_GROUP_USER, INSPECT_TOTAL_RECORD, PATROL_RECORD, SAFE_RECORD_BASIC, SECURITY_PATROL, SAFE_CONSTRUCT, SAFE_DANGER, SAFE_SPECIAL_TYPE, SAFE_CONSTRUCT_DEVICE];
    
    for (NSString *table in tableArray) {
        NSString *sql = [NSString stringWithFormat:@"DELETE FROM %@",table];
        BOOL success =  [db executeUpdate:sql];
        if(success){
            num++;
            
        } else {
            NSLog(@"删除失败");
        }
    }
    [db close];
    NSLog(@"数据库地址：%@",DEF_DB_DATABASEPATH);
    //沙盒文件删除
    NSFileManager *fileManager = [NSFileManager defaultManager];
    if ([fileManager removeItemAtPath:DEF_IMAGEFILE_PATH error:NULL]) {
        NSLog(@"删除拍照图片成功");
    }
    if ([fileManager removeItemAtPath:DEF_FILE_PATH error:NULL]) {
        NSLog(@"删除附件成功");
    }
    if ([fileManager removeItemAtPath:DEF_FILE_PDF_PATH error:NULL]) {
        NSLog(@"删除PDF成功");
    }
    
    WEAKSELF
    if(tableArray.count == num){
        NSLog(@"数据库清除成功");
        /*
         *  初始化数据
         */
        NSMutableDictionary *parameDic=[NSMutableDictionary dictionary];
        [LSUtility hideMBProgress:weakSelf.view];
        [LSUtility showMBProgress:weakSelf.view message:@"数据获取中.."];
        [LSHttpTool Post:URL_DATA_SYNCHRONIZATION parameters:parameDic success:^(id responseObject) {
            
            [MBProgressHUD hideHUDForView:weakSelf.view animated:YES];
            NSLog(@"初始化：%@",responseObject);
            if(responseObject){
                NSString *code=responseObject[@"code"];
                if(code){
                    if([code isEqualToString:@"1"]){
                        dataInit *initData=[[dataInit alloc]init];
                        NSDictionary *dic=responseObject[@"data"];
                        //没有返回数据
                        if([[dic allKeys] containsObject:@"total"]){
                            [LSUtility showToastWithMessage:@"请先在pc端设置数据" inView:weakSelf.view Andtime:1.5];
                            return ;
                        }
                        //传入数据
                        [initData initWithResponseObject:responseObject[@"data"]];
                        [MBProgressHUD hideHUDForView:weakSelf.view animated:YES];
                        
                        initData.blockMainTab=^(){
                            // 初始化用户名写入文件
                            [weakSelf durationUser:weakSelf.userName.text];
                            //初始化完成 跳转
                            EsTabBarController *tabMain=[[EsTabBarController alloc]init];
                            [tabMain setProId: roleOrPro[@"proId"]  setProType:roleOrPro[@"proType"] andUserId:userDic[@"userId"] andRole:roleOrPro[@"userType"]];
                            [[UIApplication sharedApplication].delegate window].rootViewController=tabMain;
                        };
                    }else{
                        [LSUtility hideMBProgress:weakSelf.view];
//                        [LSUtility showToastWithMessage:responseObject[@"msg"] inView:weakSelf.view Andtime:2.];
                        return ;
                    }
                }else{
                        [MBProgressHUD showError:@"服务器异常!" toView:self.view];
                }
            }else{
//                [LSUtility showToastWithMessage:responseObject[@"msg"] inView:self.view Andtime:2.];
            }
        } failure:^(NSError *error) {
            NSLog(@"超时");
            [LSUtility hideMBProgress:weakSelf.view];
        }];
    }
}



#pragma mark - 引导页
/**
 *  判断是否显示引导页
 */
- (void)judgeWelcomePageView{
    self.scrollView.bounces=NO;
    //版本
    NSString *key = (NSString *)kCFBundleVersionKey;
    //新版本号
    NSString *version = [NSBundle mainBundle].infoDictionary[key];
    //老版本号
    NSString *oldVersion =DEF_PERSISTENT_GET_OBJECT(@"firstLanch");
    //是否是首次使用APP、是否是首次使用APP
    BOOL is=![version isEqualToString:oldVersion]||DEF_PERSISTENT_GET_OBJECT(@"FirstLoad") == nil;
    if (is) {
        DEF_PERSISTENT_SET_OBJECT(version, @"firstLanch");
        DEF_PERSISTENT_SET_OBJECT(@"FirstLoad", @"FirstLoad");
        //显示引导页
        [self showIntroWithCrossDissolve];
    }else{
        return;
    }
}

/**
 *  设置引导页提示语等
 */
- (void)showIntroWithCrossDissolve {
    [self.view addSubview:self.scrollView];
    self.scrollView.contentSize=CGSizeMake(3*DEF_SCREEN_WIDTH, 0);
    UIImageView* img;
    UIButton *btn;
    for(int i=0;i<4;i++){
        //添加引导页
        img.userInteractionEnabled=YES;
        img = [[UIImageView alloc] initWithFrame:CGRectMake(i*DEF_SCREEN_WIDTH, 0, DEF_SCREEN_WIDTH, DEF_SCREEN_HEIGHT)];
        img.image = [UIImage imageNamed:[NSString stringWithFormat:@"引导页%d",i+1]];
        [self.scrollView addSubview:img];
        //添加btn
        if(i>=2){
            
            btn=[[UIButton alloc]initWithFrame:CGRECTS(DEF_SCREEN_WIDTH/2-62,DEF_SCREEN_HEIGHT- DEF_SCREEN_HEIGHT/4, 124, 70)];
            btn.layer.cornerRadius=20;
            btn.titleLabel.font=[UIFont systemFontOfSize:16];
            
        }else{
            
            btn=[[UIButton alloc]initWithFrame:CGRectMake(DEF_SCREEN_WIDTH-DEF_SCREEN_WIDTH/6.25, 30, 40, 26)];
            [btn setTitle:@"跳过" forState:UIControlStateNormal];
            [btn setTitleColor:[UIColor colorWithRed:0.75 green:0.75 blue:0.75 alpha:1.00]
                      forState:UIControlStateNormal];
            btn.titleLabel.font=[UIFont systemFontOfSize:14];
            
        }
        
        [img addSubview:btn];
        btn.transform = CGAffineTransformMakeScale([UIScreen mainScreen].bounds.size.width / 375, [UIScreen mainScreen].bounds.size.height / 667);
        [btn addTarget:self action:@selector(clickBtnYindao) forControlEvents:UIControlEventTouchUpInside];
        
    }
}

- (void)clickBtnYindao{
    // 准备动画
    CATransition *animation = [CATransition animation];
    //动画播放持续时间
    [animation setDuration:0.5f];
    //动画速度,何时快、慢
    [animation setTimingFunction:[CAMediaTimingFunction
                                  functionWithName:kCAMediaTimingFunctionEaseIn]];
    //开始动画
    [self.view.layer addAnimation:animation forKey:@"suckEffect"];
    [self.scrollView removeFromSuperview];
    // 结束动画
    [UIView commitAnimations];
}
- (NSString*)iphoneType {
    
    //需要导入头文件：#import <sys/utsname.h>
    
    struct utsname systemInfo;
    
    uname(&systemInfo);
    
    NSString*platform = [NSString stringWithCString: systemInfo.machine encoding:NSASCIIStringEncoding];
    
    if([platform isEqualToString:@"iPhone1,1"])  return@"iPhone 2G";
    
    if([platform isEqualToString:@"iPhone1,2"])  return@"iPhone 3G";
    
    if([platform isEqualToString:@"iPhone2,1"])  return@"iPhone 3GS";
    
    if([platform isEqualToString:@"iPhone3,1"])  return@"iPhone 4";
    
    if([platform isEqualToString:@"iPhone3,2"])  return@"iPhone 4";
    
    if([platform isEqualToString:@"iPhone3,3"])  return@"iPhone 4";
    
    if([platform isEqualToString:@"iPhone4,1"])  return@"iPhone 4S";
    
    if([platform isEqualToString:@"iPhone5,1"])  return@"iPhone 5";
    
    if([platform isEqualToString:@"iPhone5,2"])  return@"iPhone 5";
    
    if([platform isEqualToString:@"iPhone5,3"])  return@"iPhone 5c";
    
    if([platform isEqualToString:@"iPhone5,4"])  return@"iPhone 5c";
    
    if([platform isEqualToString:@"iPhone6,1"])  return@"iPhone 5s";
    
    if([platform isEqualToString:@"iPhone6,2"])  return@"iPhone 5s";
    
    if([platform isEqualToString:@"iPhone7,1"])  return@"iPhone 6 Plus";
    
    if([platform isEqualToString:@"iPhone7,2"])  return@"iPhone 6";
    
    if([platform isEqualToString:@"iPhone8,1"])  return@"iPhone 6s";
    
    if([platform isEqualToString:@"iPhone8,2"])  return@"iPhone 6s Plus";
    
    if([platform isEqualToString:@"iPhone8,4"])  return@"iPhone SE";
    
    if([platform isEqualToString:@"iPhone9,1"])  return@"iPhone 7";
    
    if([platform isEqualToString:@"iPhone9,2"])  return@"iPhone 7 Plus";
    
    if([platform isEqualToString:@"iPhone10,1"]) return@"iPhone 8";
    
    if([platform isEqualToString:@"iPhone10,4"]) return@"iPhone 8";
    
    if([platform isEqualToString:@"iPhone10,2"]) return@"iPhone 8 Plus";
    
    if([platform isEqualToString:@"iPhone10,5"]) return@"iPhone 8 Plus";
    
    if([platform isEqualToString:@"iPhone10,3"]) return@"iPhone X";
    
    if([platform isEqualToString:@"iPhone10,6"]) return@"iPhone X";
    
    if([platform isEqualToString:@"iPod1,1"])  return@"iPod Touch 1G";
    
    if([platform isEqualToString:@"iPod2,1"])  return@"iPod Touch 2G";
    
    if([platform isEqualToString:@"iPod3,1"])  return@"iPod Touch 3G";
    
    if([platform isEqualToString:@"iPod4,1"])  return@"iPod Touch 4G";
    
    if([platform isEqualToString:@"iPod5,1"])  return@"iPod Touch 5G";
    
    if([platform isEqualToString:@"iPad1,1"])  return@"iPad 1G";
    
    if([platform isEqualToString:@"iPad2,1"])  return@"iPad 2";
    
    if([platform isEqualToString:@"iPad2,2"])  return@"iPad 2";
    
    if([platform isEqualToString:@"iPad2,3"])  return@"iPad 2";
    
    if([platform isEqualToString:@"iPad2,4"])  return@"iPad 2";
    
    if([platform isEqualToString:@"iPad2,5"])  return@"iPad Mini 1G";
    
    if([platform isEqualToString:@"iPad2,6"])  return@"iPad Mini 1G";
    
    if([platform isEqualToString:@"iPad2,7"])  return@"iPad Mini 1G";
    
    if([platform isEqualToString:@"iPad3,1"])  return@"iPad 3";
    
    if([platform isEqualToString:@"iPad3,2"])  return@"iPad 3";
    
    if([platform isEqualToString:@"iPad3,3"])  return@"iPad 3";
    
    if([platform isEqualToString:@"iPad3,4"])  return@"iPad 4";
    
    if([platform isEqualToString:@"iPad3,5"])  return@"iPad 4";
    
    if([platform isEqualToString:@"iPad3,6"])  return@"iPad 4";
    
    if([platform isEqualToString:@"iPad4,1"])  return@"iPad Air";
    
    if([platform isEqualToString:@"iPad4,2"])  return@"iPad Air";
    
    if([platform isEqualToString:@"iPad4,3"])  return@"iPad Air";
    
    if([platform isEqualToString:@"iPad4,4"])  return@"iPad Mini 2G";
    
    if([platform isEqualToString:@"iPad4,5"])  return@"iPad Mini 2G";
    
    if([platform isEqualToString:@"iPad4,6"])  return@"iPad Mini 2G";
    
    if([platform isEqualToString:@"iPad4,7"])  return@"iPad Mini 3";
    
    if([platform isEqualToString:@"iPad4,8"])  return@"iPad Mini 3";
    
    if([platform isEqualToString:@"iPad4,9"])  return@"iPad Mini 3";
    
    if([platform isEqualToString:@"iPad5,1"])  return@"iPad Mini 4";
    
    if([platform isEqualToString:@"iPad5,2"])  return@"iPad Mini 4";
    
    if([platform isEqualToString:@"iPad5,3"])  return@"iPad Air 2";
    
    if([platform isEqualToString:@"iPad5,4"])  return@"iPad Air 2";
    
    if([platform isEqualToString:@"iPad6,3"])  return@"iPad Pro 9.7";
    
    if([platform isEqualToString:@"iPad6,4"])  return@"iPad Pro 9.7";
    
    if([platform isEqualToString:@"iPad6,7"])  return@"iPad Pro 12.9";
    
    if([platform isEqualToString:@"iPad6,8"])  return@"iPad Pro 12.9";
    
    if([platform isEqualToString:@"i386"])  return@"iPhone Simulator";
    
    if([platform isEqualToString:@"x86_64"])  return@"iPhone Simulator";
    
    return platform;
    
}
@end
